#!/usr/bin/env python3

# Copyright (c) 2020-2021 Fpemud <fpemud@sina.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.


import os
import pathlib
from ._util import Util
from ._po import AuthorizedKeyInfo


class ServerUserCfg:

    def __init__(self, prefix="/", user=None, cfg_dir=None, read_only=False):
        if cfg_dir is None:
            assert user is not None

        self._prefix = prefix

        if cfg_dir is None:
            self._cfgDir = os.path.join(self._prefix, "home", user, ".ssh")
        else:
            assert not cfg_dir.startswith("/")
            self._cfgDir = os.path.join(self._prefix, cfg_dir)

        self._readOnly = read_only

    @property
    def paths(self):
        return [
            self._cfgDir,
            self._getAuthorizedKeysFilePath(),
        ]

    def get_authorized_keys(self):
        try:
            ret = []
            for line in Util.readListFile(self._getAuthorizedKeysFilePath()):
                ret.append(AuthorizedKeyInfo(line=line))
            return ret
        except FileNotFoundError:
            return []

    def add_or_update_authorized_key(self, key_type, key, comment=""):
        try:
            lineList = Util.readListFile(self._getAuthorizedKeysFilePath())
        except FileNotFoundError:
            lineList = []

        bFound = False
        bModified = False
        for i, line in enumerate(lineList):
            obj = AuthorizedKeyInfo(line=line)
            if obj.key_type == key_type and obj.key == key:
                bFound = True
                if obj._comment != comment:
                    obj._comment = comment
                    lineList[i] = obj._toLine()
                    bModified = True

        if not bFound:
            lineList.append(AuthorizedKeyInfo(key_type=key_type, key=key, comment=comment)._toLine())
            bModified = True

        if bModified:
            self._writeAuthorizedKeysFile(lineList)

    def check(self, auto_fix=False, error_callback=None):
        if auto_fix:
            assert not self._readOnly

        if error_callback is None:
            error_callback = Util.doNothing

        # check authorized_keys file
        keyInfoSet = set()
        for obj in self.get_authorized_keys():
            if (obj.key_type, obj.key) in keyInfoSet:
                error_callback('duplicate key found in "%s"' % (self._getAuthorizedKeysFilePath()))
            keyInfoSet.add((obj.key_type, obj.key))

    def _getAuthorizedKeysFilePath(self):
        return os.path.join(self._cfgDir, "authorized_keys")

    def _writeAuthorizedKeysFile(self, lineList):
        os.makedirs(self._cfgDir, exist_ok=True)
        pathlib.Path(self._getAuthorizedKeysFilePath()).write_text("\n".join(lineList) + "\n")
